package at.fhooe.mc.msports.heartrate;

import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;

import javax.microedition.io.StreamConnection;

import at.fhooe.mc.bluetooth.Bluetooth;

public class ZephyrHRM extends Thread implements IHeartRateMonitor {

	private boolean listenToZephyr = true;
	private StreamConnection connection;
	private InputStream is;
	private ZephyrHeartRateDataParser parser;
	private Vector listeners;
	
	public ZephyrHRM() {
		if(Bluetooth.open()){
			try{
				connection = Bluetooth.bluetoothConnection;
				is = connection.openInputStream();
				parser = new ZephyrHeartRateDataParser();
				start();
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}
	
	public void setRunning(boolean r){
		listenToZephyr = r;
		
		if (is != null) {
			try {
				is.close();
			} catch(IOException ioe) {}
		}
		
		Bluetooth.close();
	}
	
	public void run(){
		try{
			while(listenToZephyr){
				
				byte[] packet;
				
				packet = parser.readPacket(is);
				if (packet != null) {
						RawHeartRateData data = parser.parsePacket(packet);
						for(int i = 0; i < listeners.size(); i++){
							((IHeartRateListener)listeners.elementAt(i)).onHeartRateUpdated(
									data.getHeartRate());
						}
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public int getHeartRate() {
		// TODO Auto-generated method stub
		return 0;
	}

	public void addListener(IHeartRateListener listener) {
		if(listener != null)
			listeners.addElement(listener);
	}

}
